<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;

class Goods extends BaseModel
{
    protected $table = "goods";

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    public function getGoodsInfoById($id)
    {
        $res = $this->getOne(['id' => $id]);
        if ($res) {
            $res['spu'] = $res['id'] + 100000;
            $res['pics'] = explode(',', trim($res['pics'], ','));
        }
        return $res;
    }


    public function getGoodsList($request)
    {
        $keyword = $request['keyword'] ? $request['keyword'] : '';
        $where = [];
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['name'] = ['like', '%' . $keyword . '%'];
            }
        }
        if (session('adminId')) {
            $where['bid'] = session('adminId');
        } else {
            $agent = new Agent();
            $agentInfo = $agent->getAgentInfo(session('agent')['aid']);

            $arr = $agentInfo['data']['bid'];

            if (strstr($agentInfo['data']['bid'], ',')) {
                $arr = explode(',', $agentInfo['data']['bid'])[1];

                if (is_array($arr)) {
                    array_pop($arr);
                    array_shift($arr);
                } else {
                    $arr = $arr;
                }

            }
            $where['bid'] = is_array($arr) ? ['in', $arr] : $arr;
        }
        $order['id'] = 'desc';
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            foreach ($rows['data'] as $k => $v) {
                $rows['data'][$k]['spu'] = 100000 + $v['id'];
                if ($v['pics']) {
                    $rows['data'][$k]['pics'] = explode(',', trim($v['pics'], ','));
                }
                for ($i = 1; $i < 4; $i++) {
                    $name_str = 'spec' . $i . '_name';
                    $value_str = 'spec' . $i . '_value';
                    if ($v[$name_str]) {
                        $data[$name_str] = $v[$name_str];
                        if ($v[$value_str]) {
                            $rows['data'][$k][$value_str] = explode(',', trim($v[$value_str], ','));
                        }
                    }
                }
            }
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        return $rows;
    }

    public function addGoods($request)
    {

        $data['cid_1'] = $request['cid_1'];
        $data['cid_2'] = $request['cid_2'] ? $request['cid_2'] : 0;
        $data['cid_3'] = $request['cid_3'] ? $request['cid_3'] : 0;
        $data['name'] = $request['name'];
        $data['price'] = $request['price'];
        $data['num'] = $request['num'];
        $data['low_num'] = $request['low_num'] > 0 ? $request['low_num'] : 0;
        $data['content'] = htmlspecialchars($request['content']);
        for ($i = 1; $i < 4; $i++) {
            $name_str = 'spec' . $i . '_name';
            $value_str = 'spec' . $i . '_value';
            if ($request[$name_str]) {
                $data[$name_str] = $request[$name_str];
                if ($request[$value_str]) {
                    $data[$value_str] = str_replace('，', ',', str_replace(' ', '', $request[$value_str]));
                }
            }
        }

        $imgPath = array();
        if ($request['pics']) {
            //dd($request['pics']);
            foreach ($request['pics'] as $v) {

                $imgPath[] = upImgs($v, 'goods');

            }


            if (!empty($imgPath)) {
                if (is_array($imgPath)) {
                    //dd(123);
                    $data['pics'] = implode(',', $imgPath);

                } else {
                    $data['pics'] = $imgPath;
                }

            }
        }


        $data['created_at'] = date('Y-m-d H:i:s', time());
        $data['updated_at'] = date('Y-m-d H:i:s', time());
        $data['bid'] = session('adminId');

        $oneinfo =$this->getOne(['bid'=>$data['bid'],'name'=>$data['name']]);
        if($oneinfo){
            return ['status'=>0,'msg'=>'已有名字为'.$oneinfo['name'].'的商品,请选择其他名字'];
        }

        $res = $this->add($data);
        $ajaxData['status'] = $res ? 1 : 0;
        $ajaxData['msg'] = '发布成功！';
        if (!$res) {
            $ajaxData['msg'] = '发布失败！';
        }
        return $ajaxData;

    }

    public function changeStatus($request)
    {
        $where['id'] = $request['id'];
        $res = $this->del($where);
        $ajaxData['status'] = $res ? 1 : 0;
        $ajaxData['msg'] = '删除成功！';
        if (!$res) {
            $ajaxData['msg'] = '删除失败！';
        }
        return $ajaxData;
    }

    //批量删除,小杰作品
    public function delAll($request)
    {

        $str = $request['id'];
        $ids = explode(',', $str);


        foreach ($ids as $v) {

            $res = DB::table('goods')->where('id', '=', "$v")->delete();

        }


        $ajaxData['status'] = $res ? 1 : 0;
        $ajaxData['msg'] = '批量删除成功！';
        if (!$res) {
            $ajaxData['msg'] = '批量删除失败！';
        }
        return $ajaxData;

    }

    public function checkGoodsNum($goodsId, $goodsNum)
    {
        $data['status'] = 1;
        $goodsInfo = $this->getGoodsInfoById($goodsId);
        if ($goodsInfo['low_num'] > intval($goodsNum)) {
            $data['status'] = 0;
            $data['msg'] = '下单数量不得少于' . $goodsInfo['low_num'];
        }
        $data['total_money'] = $goodsNum * $goodsInfo['price'];
        return $data;
    }

    public function postSave($request)
    {

        $data['cid_1'] = $request['cid_1'];
        $data['cid_2'] = $request['cid_2'];
        $data['cid_3'] = $request['cid_3'];
        $data['name'] = $request['name'];
        $data['price'] = $request['price'];
        $data['num'] = $request['num'];
        $data['low_num'] = $request['low_num'];
        $data['content'] = htmlspecialchars($request['content']);
        $where['id'] = $request['id'];
        $data1 = $this->getList($where)->toArray();

        for ($i = 1; $i < 4; $i++) {
            $name_str = 'spec' . $i . '_name';
            $value_str = 'spec' . $i . '_value';
            if ($request[$name_str]) {
                $data[$name_str] = $request[$name_str];
                if ($request[$value_str]) {
                    $data[$value_str] = str_replace('，', ',', str_replace(' ', '', $request[$value_str]));
                }
            }
        }
        /***保证商品名唯一性***/
        $data['bid'] = session('adminId');
        $oneinfo =$this->getOne(['bid'=>$data['bid'],'name'=>$data['name'],'id'=>['!=',$request['id']]]);
        if($oneinfo){
            return ['status'=>0,'msg'=>'已有名字为'.$oneinfo['name'].'的商品,请选择其他名字'];
        }
        /***保证商品名唯一性***/

        /****老图片***/
        $oldimgs = [];
        if($request['oldpic']){
            $oldimgs = $request['oldpic'];    //一张图片也是个数组
        }
        /****老图片end***/

        /***新图片***/
        $imgPath = array();

        if ($request['pics']) {

            foreach ($request['pics'] as $v) {

                $imgPath[] = upImgs($v, 'goods');

            }

            if (!empty($imgPath)) {
                if (is_array($imgPath)) {
                    if ($data1[0]['pics']) {
                        $data['pics'] = $data1[0]['pics'] . "," . implode(',', $imgPath);
                    } else {
                        $data['pics'] = implode(',', $imgPath);
                    }
                } else {
                    if ($data1[0]['pics']) {
                        $data['pics'] = $data1[0]['pics'] . "," . $imgPath;
                    } else {
                        $data['pics'] = $imgPath;
                    }
                }

            }
        }
        //dd($imgPath);


        /***新图片end***/

        /**合并图片**/
        if($oldimgs&&$imgPath){
            $data['pics'] = array_merge($oldimgs,$imgPath);
            $data['pics'] = implode(',',$data['pics']);
        }elseif($oldimgs){
            $data['pics'] = $oldimgs;
            $data['pics'] = implode(',',$data['pics']);
        }elseif($imgPath){
            $data['pics'] = $imgPath;
            $data['pics'] = implode(',',$data['pics']);
        }else{
            $data['pics'] = '';
        }

        //dd($data);
        /**合并图片end**/

        $data['created_at'] = date('Y-m-d H:i:s', time());

        $data = trim_fileds($data);

        $res = $this->up($where, $data);

        $ajaxData['status'] = $res ? 1 : 0;

        $ajaxData['msg'] = '编辑成功！';

        if (!$res) {
            $ajaxData['msg'] = '编辑失败！';
        }
        return $ajaxData;
    }

}